package com.bilibili.juc.cf.one;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class FutureHandlerTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<String> orgFuture = CompletableFuture.supplyAsync(
                ()->{
                    System.out.println("supplyAsync 当前线程名称：" + Thread.currentThread().getName());
                    try {
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return "捡田螺的小男孩";
                }
        );

        CompletableFuture<String> handler1Future = orgFuture.handle((a, throwable) -> {
            System.out.println("handle1 当前线程名称：" + Thread.currentThread().getName());
            System.out.println("上个任务执行完啦，还把 \"" + a + "\" 传过来");
            if ("捡田螺的小男孩".equals(a)) {
                System.out.println("111");
                return a+"==>>handler1关注了";
            }
            System.out.println("222");
            return a+"==>>handler1再考虑一下";
        });

        CompletableFuture<String> handler2Future = handler1Future.handle((a, throwable) -> {
            System.out.println("handle2 当前线程名称：" + Thread.currentThread().getName());
            System.out.println("上个任务执行完啦，还把 \"" + a + "\" 传过来");
            if ("捡田螺的小男孩".equals(a)) {
                System.out.println("333");
                return a+"==>>handler2关注了";
            }
            System.out.println("444");
            return a+"==>>handler2再考虑一下";
        });

        System.out.println("handler1Future结果："+handler1Future.get());
        System.out.println("handler2Future结果："+handler2Future.get());
    }
}
/*
supplyAsync 当前线程名称：ForkJoinPool.commonPool-worker-1
handle1 当前线程名称：ForkJoinPool.commonPool-worker-1
上个任务执行完啦，还把 "捡田螺的小男孩" 传过来
111
handle2 当前线程名称：ForkJoinPool.commonPool-worker-1
上个任务执行完啦，还把 "捡田螺的小男孩==>>handler1关注了" 传过来
444
handler1Future结果：捡田螺的小男孩==>>handler1关注了
handler2Future结果：捡田螺的小男孩==>>handler1关注了==>>handler2再考虑一下
 */
